class WebSocketManager {
  constructor() {
    this.ws = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.messageHandlers = new Map();
    this.heartbeatTimer = null;
    this.heartbeatInterval = 30000; // 30秒发送一次心跳
    this.heartbeatTimeout = 5000; // 5秒内没收到响应就重连
    this.heartbeatTimeoutTimer = null;
  }

  // 连接WebSocket
  connect() {
    return new Promise((resolve, reject) => {
      // 根据环境选择不同的 WebSocket 地址
      const wsUrl = process.env.NODE_ENV === 'development' 
        ? 'ws://localhost:8888/ws'  // 开发环境
        : 'ws://your_domain.com/ws'; // 生产环境，替换为您的域名
      
      let user = wx.getStorageSync("user");
      const token = user ? user.token : '';
      
      if (!token) {
        console.error('未找到token，请先登录');
        wx.navigateTo({
          url: '/pages/sub/mine/loginp/loginp'
        });
        reject(new Error('未找到token'));
        return;
      }

      this.ws = wx.connectSocket({
        url: wsUrl,
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: () => {
          console.log('WebSocket连接成功');
          this.isConnected = true;
          this.reconnectAttempts = 0;
          this.startHeartbeat();
          resolve();
        },
        fail: (error) => {
          console.error('WebSocket连接失败:', error);
          if(error.errMsg && (error.errMsg.includes('401'))) {
            wx.navigateTo({
              url: '/pages/sub/mine/loginp/loginp'
            });
            return;
          }
          reject(error);
        }
      });

      this.ws.onOpen(() => {
        console.log('WebSocket连接已打开');
        this.isConnected = true;
        this.reconnectAttempts = 0;
        this.startHeartbeat();
      });

      this.ws.onClose((res) => {
        console.log('WebSocket连接已关闭', {
          code: res.code,
          reason: res.reason,
          errMsg: res.errMsg,
          reconnectAttempts: this.reconnectAttempts
        });
        this.isConnected = false;
        this.stopHeartbeat();
          
        // 检查关闭原因
        if (res.reason === '401') {
          console.log('认证失败，跳转到登录页面');
          wx.navigateTo({
            url: '/pages/sub/mine/loginp/loginp'
          });
          return;
        }

        // 检查是否是正常关闭
        if (res.code === 1000) {
          console.log('WebSocket正常关闭，不进行重连');
          return;
        }
        
        this.reconnect();
      });

      this.ws.onError((error) => {
        console.error('WebSocket错误:', {
          errMsg: error.errMsg,
          reconnectAttempts: this.reconnectAttempts
        });
        this.isConnected = false;
        this.stopHeartbeat();
        
        if(error.errMsg && (error.errMsg.includes('401'))) {
          console.log('认证失败，跳转到登录页面');
          wx.navigateTo({
            url: '/pages/sub/mine/loginp/loginp'
          });
          return;
        }
        
        this.reconnect();
      });

      this.ws.onMessage((res) => {
        try {
          const message = JSON.parse(res.data);
          if (message.type === 'HEARTBEAT_RESPONSE') {
            this.handleHeartbeatResponse();
          } else {
            this.handleMessage(message);
          }
        } catch (error) {
          console.error('消息解析错误:', error);
        }
      });
    });
  }

  // 开始心跳
  startHeartbeat() {
    this.stopHeartbeat();
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected) {
        this.sendHeartbeat();
      }
    }, this.heartbeatInterval);
  }

  // 停止心跳
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
    if (this.heartbeatTimeoutTimer) {
      clearTimeout(this.heartbeatTimeoutTimer);
      this.heartbeatTimeoutTimer = null;
    }
  }

  // 发送心跳
  sendHeartbeat() {
    if (!this.isConnected) return;
    
    console.log('发送心跳包');
    this.sendMessage({
      type: 'HEARTBEAT',
      data: {
        timestamp: Date.now()
      }
    });

    // 设置心跳超时
    if (this.heartbeatTimeoutTimer) {
      clearTimeout(this.heartbeatTimeoutTimer);
    }
    
    this.heartbeatTimeoutTimer = setTimeout(() => {
      console.log('心跳超时，准备重连');
      // 不要主动关闭连接，让重连机制处理
      this.isConnected = false;
      this.reconnect();
    }, this.heartbeatTimeout);
  }

  // 处理心跳响应
  handleHeartbeatResponse() {
    console.log('收到心跳响应');
    if (this.heartbeatTimeoutTimer) {
      clearTimeout(this.heartbeatTimeoutTimer);
      this.heartbeatTimeoutTimer = null;
    }
  }

  // 重连机制
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('达到最大重连次数');
      return;
    }

    this.reconnectAttempts++;
    console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);

    // 如果连接还存在，先关闭它
    if (this.ws) {
      try {
        this.ws.close();
      } catch (e) {
        console.error('关闭旧连接失败:', e);
      }
    }

    setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }

  // 发送消息
  sendMessage(message) {
    if (!this.isConnected) {
      console.error('WebSocket未连接');
      return;
    }

    this.ws.send({
      data: JSON.stringify(message),
      success: () => {
        console.log('消息发送成功');
      },
      fail: (error) => {
        console.error('消息发送失败:', error);
      }
    });
  }




  // 输入框内容变化
  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  }


  // 注册消息处理器
  onMessage(type, handler) {
    this.messageHandlers.set(type, handler);
  }

  // 处理接收到的消息
  handleMessage(message) {
    const handler = this.messageHandlers.get(message.type);
    if (handler) {
      handler(message.data);
    }
  }

  // 关闭连接
  close() {
    this.stopHeartbeat();
    if (this.ws) {
      this.ws.close();
      this.isConnected = false;
    }
  }
}

export default new WebSocketManager(); 